package com.tongzhan.service.impl;

import com.tongzhan.base.PageInfo;
import com.tongzhan.base.Return;
import com.tongzhan.data.vo.ConditionVO;
import com.tongzhan.data.vo.PicVO;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Condition;
import com.tongzhan.entity.religion.ModuleSign;
import com.tongzhan.entity.religion.Site;
import com.tongzhan.file.FileGenerate;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.ConditionRepository;
import com.tongzhan.repository.religion.ModuleSignRepository;
import com.tongzhan.repository.religion.SiteRepository;
import com.tongzhan.service.ConditionService;
import com.tongzhan.utils.DateSwitcher;
import com.tongzhan.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Slf4j
@Service
public class ConditionServiceImpl implements ConditionService {

    @Autowired
    private ConditionRepository conditionRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SiteRepository siteRepository;

    @Autowired
    private ModuleSignRepository signRepository;

    @Override
    public Return newCondition(String userId, Condition condition) {
        //用户
        User user = userRepository.findByPrimaryKey(userId);
        if (user == null) {
            return new Return(Return.FAIL, "用户不存在");
        }
        //查询场所
        Site site = siteRepository.findByPrimaryKey(condition.getSiteCode());
        String religionCode = "";
        if (site != null) {
            condition.setVillageCode(site.getVillageCode());
            condition.setVillageName(site.getVillageName());
            religionCode = site.getReligionCode();
        }
        condition.setUserName(user.getUserName());
        condition.setRealName(user.getRealName());
        condition.setCreateTime(LocalDateTime.now());
        try {
            //生成文件
            FileGenerate.generate(condition.getPicture(), condition.getUserName());
            conditionRepository.insert(condition);
        } catch (Exception e) {
            return new Return(Return.EXEXCEPTION, "新增情况报告失败");
        }
        //生成角标
        Query query = new Query();
        //民宗局、root、镇街道、宗教团体、宗教场所、村社区、民间信仰点
        List<String> codes = Arrays.asList("00", "01", "02", "03", "04", "05");
        query.addCriteria(Criteria.where("DutiesCode").in(codes));
        //排除当前用户
        query.addCriteria(Criteria.where("UserId").nin(userId));
        List<ModuleSign> signList = signRepository.findAll(query);
        if (!CollectionUtils.isEmpty(signList)) {
            for (ModuleSign sign : signList) {
                String dutiesCode = sign.getDutiesCode();
                if ("02".equals(dutiesCode) && !condition.getSiteCode().equals(sign.getStreetCode())) {
                    continue;
                }
                if ("03".equals(dutiesCode) && !religionCode.equals(sign.getReligionCode())) {
                    continue;
                }
                if (("04".equals(dutiesCode) || "07".equals(dutiesCode)) && !condition.getSiteCode().equals(sign.getSiteCode())) {
                    continue;
                }
                //情况报告角标加一
                sign.setCondition(sign.getCondition() + 1);
                signRepository.updateByPrimaryKey(sign);
            }
        }
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return getConditionList(String userId, String timeSlot, Integer page, Integer size) {
        //查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "CreateTime"));
        //用户信息
        User user = userRepository.findByPrimaryKey(userId);
        if (user != null) {
            if ("02".equals(user.getDutiesCode()) || ThreadLocalUtil.STREET_CODE.equals(user.getDutiesCode())) {
                //镇街道
                query.addCriteria(Criteria.where("StreetCode").is(user.getStreetCode()));
            } else if ("05".equals(user.getDutiesCode()) || ThreadLocalUtil.VILLAGE_CODE.equals(user.getDutiesCode())) {
                //村社区
                query.addCriteria(Criteria.where("VillageCode").is(user.getVillageCode()));
            } else if ("04".equals(user.getDutiesCode()) || "07".equals(user.getDutiesCode())) {
                //场所、信仰点
                query.addCriteria(Criteria.where("SiteCode").is(user.getSiteCode()));
            }
        }
//        //现在时间
//        LocalDateTime now = LocalDateTime.now();
//        //筛选后的时间
//        LocalDateTime time;
//        if ("一周".equals(timeSlot)) {
//            //一周
//            time = now.minusDays(7);
//        } else if ("一月".equals(timeSlot)) {
//            //一月
//            time = now.minusMonths(1);
//        } else if ("一季".equals(timeSlot)) {
//            //一季
//            time = now.minusMonths(4);
//        } else if ("半年".equals(timeSlot)) {
//            //半年
//            time = now.minusMonths(6);
//        } else {
//            //一年
//            time = now.minusYears(1);
//        }
        if (StringUtils.isNotEmpty(timeSlot)) {
            timeSlot = timeSlot + "-01";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date;
            try {
                date = LocalDate.parse(timeSlot, dtf);
            } catch (Exception e) {
                return new Return(Return.FAIL, "日期格式为yyyy-MM");
            }
            query.addCriteria(Criteria.where("CreateTime").gte(DateSwitcher.getMinTime(date.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay()))
                    .andOperator(Criteria.where("CreateTime").lte(DateSwitcher.getMaxTime(date.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay()))));
        }
        //情况报告列表
        Page<Condition> conditionPage = conditionRepository.findPage(query, PageRequest.of(page - 1, size));
        //返回VO
        List<ConditionVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(conditionPage.getContent())) {
            for (Condition condition : conditionPage.getContent()) {
                ConditionVO vo = new ConditionVO();
                vo.setConditionCode(condition.get_id());
                vo.setUserName(condition.getUserName());
                vo.setRealName(condition.getRealName());
                vo.setStreetCode(condition.getStreetCode());
                vo.setStreetName(condition.getStreetName());
                vo.setSiteCode(condition.getSiteCode());
                vo.setSiteName(condition.getSiteName());
                vo.setTitle(condition.getTitle());
                vo.setContent(condition.getContent());
                vo.setTime(condition.getCreateTime().toLocalDate());
                //图片编号
                String fileUrls = condition.getPicture();
                List<PicVO> picList = new ArrayList<>();
                if (StringUtils.isNotEmpty(fileUrls)) {
                    String[] files = fileUrls.split(",");
                    for (String file : files) {
                        PicVO picVO = new PicVO();
                        picVO.setPath(file);
                        picList.add(picVO);
                    }
                }
                vo.setPicList(picList);
                vos.add(vo);
            }
        }
        if (StringUtils.isNotEmpty(userId)) {
            //对应用户的角标重置
            ModuleSign sign = signRepository.findByPrimaryKey(userId);
            if (sign != null) {
                //情况报告角标重置
                sign.setCondition(0L);
                signRepository.updateByPrimaryKey(sign);
            }
        }
        //分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setSize(vos.size());
        pageInfo.setTotal(conditionPage.getTotalElements());
        //封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("conditionList", vos);
        map.put("pageInfo", pageInfo);
        return new Return(map);
    }

    @Override
    public Return conditionDetails(String conditionCode) {
        Condition condition = conditionRepository.findByPrimaryKey(conditionCode);
        ConditionVO vo = new ConditionVO();
        if (condition != null) {
            vo.setConditionCode(condition.get_id());
            vo.setUserName(condition.getUserName());
            vo.setRealName(condition.getRealName());
            vo.setStreetCode(condition.getStreetCode());
            vo.setStreetName(condition.getStreetName());
            vo.setSiteCode(condition.getSiteCode());
            vo.setSiteName(condition.getSiteName());
            vo.setTitle(condition.getTitle());
            vo.setContent(condition.getContent());
            vo.setTime(condition.getCreateTime().toLocalDate());
            //图片编号
            String fileUrls = condition.getPicture();
            List<PicVO> picList = new ArrayList<>();
            if (StringUtils.isNotEmpty(fileUrls)) {
                String[] files = fileUrls.split(",");
                for (String file : files) {
                    PicVO picVO = new PicVO();
                    picVO.setPath(file);
                    picList.add(picVO);
                }
                vo.setPicList(picList);
            }
        }
        return new Return(vo);
    }

    @Override
    public Return update(String conditionCode, String streetCode, String siteCode, String title, String content, String fileUrls) {
        Condition condition = conditionRepository.findByPrimaryKey(conditionCode);
        if (condition == null) {
            return new Return(Return.FAIL, "情况报告信息不存在");
        }
        //场所信息
        Site site = siteRepository.findByPrimaryKey(siteCode);
        if (site != null) {
            BeanUtils.copyProperties(site, condition, "createTime");
        }
        condition.setTitle(title);
        condition.setContent(content);
        condition.setPicture(fileUrls);
        condition.setUpdateTime(LocalDateTime.now());
        conditionRepository.updateByPrimaryKey(condition);
        return new Return(Return.SUCCESS, "修改成功");
    }

    @Override
    public void delete(String conditionCode) {
        conditionRepository.deletePrimaryKey(conditionCode);
    }
}
